<template>
    <div>
        <el-form ref="ruleFormRef" :model="formData" :rules="rules" class="from" label-width="120px" status-icon>
            <el-form-item label="文章标题" prop="title">
                <el-input v-model="formData.title" />
            </el-form-item>
            <el-form-item label="上传图片">
                <el-upload action="#" list-type="picture-card" :auto-upload="false" :on-change="uploadImg">
                    <el-icon>
                        <Plus />
                    </el-icon>

                    <template #file="{ file }">
                        <div>
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                            <span class="el-upload-list__item-actions">
                                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                    <el-icon><zoom-in /></el-icon>
                                </span>
                                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                                    <el-icon>
                                        <Download />
                                    </el-icon>
                                </span>
                                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </span>
                            </span>
                        </div>
                    </template>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </el-form-item>
            <el-form-item label="文章描述">
                <el-input />
            </el-form-item>
            <el-form-item label="文章内容" prop="content">
                <div class="app-container">
                    <editor id="tinymce" v-model="formData.content" :init="init"></editor>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button @click="addArticle">添加文章</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { upload, add } from '../utils/api'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import tinymce from "tinymce/tinymce";
import "tinymce/themes/silver/theme";
import Editor from "@tinymce/tinymce-vue"; // 引入组件
// 都是富文本插件
import "tinymce/icons/default";
import "tinymce/plugins/image";
import "tinymce/plugins/link";
import "tinymce/plugins/code";
import "tinymce/plugins/table";
import "tinymce/plugins/lists";
import "tinymce/plugins/wordcount";

const store = useStore()
const router = useRouter()

// 上传图片
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const handleRemove = (file: UploadFile) => {
    console.log(file)
}

const handlePictureCardPreview = (file: UploadFile) => {
    dialogImageUrl.value = file.url!
    dialogVisible.value = true
}

const handleDownload = (file: UploadFile) => {
    console.log(file)
}

const formData = reactive({
    title: "",
    column: "",
    content: "",
    image: "",
    author: ""
});
const uploadImg = (file: any) => {
    if (file) {
        let formDataUp = new FormData();
        formDataUp.append("file", file.raw);
        console.log(file.raw);
        // upLoad.value = "none";
        upload(formDataUp).then((res) => {
            formData.image = res.data._id;
            // formData.img = "" + res.data.url;
        });
    }
};
// 、、、



// const ruleForm = reactive({
//     title: '',
//     excerpt: '',
//     desc: ''
// })
const rules = reactive({
    title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入文章描述', trigger: 'blur' }
    ],
})

const id = store.state.column
// 添加
const addArticle = () => {

    formData.column = store.state.column
    formData.author = store.state.id
    console.log(133, formData);

    add(formData).then((res) => {
        console.log(135, res);
        router.push({
            path: '/details',
            query: { id }
        })
    })
}

// 富文本编辑器
// const tinymceHtml = ref("请输入内容");
const init = {
    //初始化数据
    language_url: "/langs/zh-Hans.js", // 引入语言包（该语言包在public下，注意文件名称）
    language: "zh-Hans", // 这里名称根据 zh-Hans.js 里面写的名称而定
    skin_url: "/skins/ui/oxide", // 这里引入的样式
    height: 300, // 限制高度
    plugins: "link lists image code table wordcount", // 富文本插件
    toolbar:
        "bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image code | removeformat",
    branding: false, // //是否禁用“Powered by TinyMCE”
    menubar: true, //顶部菜单栏显示
    // paste_convert_word_fake_lists: false, // 插入word文档需要该属性
    content_css: "/skins/content/default/content.css", //以css文件方式自定义可编辑区域的css样式，css文件需自己创建并引入
    images_upload_handler: (blobInfo) =>
        new Promise((resolve, reject) => {
            // console.log(blobInfo.blob());
            // 上传图片需要，FormData 格式的文件；
            const formDataUp = new FormData();
            // img  是接口需要的上传的属性名，一般属性名是 file
            formDataUp.append("img", blobInfo.blob());
            // // console.log(formDataUp);
            axios.post("xxxx", formDataUp).then((res) => {
                resolve("返回的上传图片后的地址");
            });
        }),
};
onMounted(() => {
    tinymce.init({}); // 初始化富文本
});
</script>
<style lang="scss" scoped>
.from {
    width: 1000px;
    position: absolute;
    left: 50%;
    margin-left: -500px;

    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader {
        border: 1px dashed #8c939d;
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
}
</style>